<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\OverSeasIn;

use App\Func\UploadFile;
use App\Logic\Plat\Rakuten\Overseas\GuCang\InboundOrder\OverseasInboundOrder;
use App\Models\Basics\SysPlat;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\OverSeasIn\Delivery;
use App\Models\OverSeasIn\DeliveryBox;
use App\Models\OverSeasIn\DeliveryBoxDetail;
use App\Models\OverSeasIn\DeliveryDetail;
use App\Models\OverSeasIn\DeliveryLabels;
use App\Models\OverSeasIn\DeliveryLogistics;
use App\Models\OverSeasIn\DeliveryTransport;
use App\Util\SerialNo;
use App\Models\Inventory\InventoryCn;
use App\Models\Inventory\Record;
use App\Models\Inventory\Placing;
use App\Models\Sys\Logs;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class OSDropshippingAjax {

    const LOG_FLAG = 'os-in-dropshipping-delivery';

    //上传标签(view)
    public function listUploadLabels($id){
        return view('overseas-in.os-dropshipping.modal-labels',compact('id'));
    }

    /**
     * 上传标签
     * @param UploadedFile $file
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doUploadLabels(UploadedFile $file,$param){
        if($file->isValid()){
            try{
                DB::beginTransaction();
                $model = Delivery::query()->findOrFail($param['id']);
                if(!$model || $model->status != 1){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '发货单状态有误(标签1)！']);
                }
                $uploadFile = UploadFile::getInit();
                $path = $uploadFile->upload($file,'labels');
                if(!$path){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败！']);
                }
                //上传标签
                $label = $model->labels()->create([
                    'labels_name' => $param['labels_name'],
                    'd_labels' => $path
                ]);
                if(!$label){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败！']);
                }else{
                    Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 上传标签",$param['id']);
                    DB::commit();
                    return response()->json(['status' => true, 'message' => '操作成功！']);
                }
            }catch (QueryException $qe){
                DB::rollBack();
                report($qe);
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
                return response()->json(['status' => false, 'message' => '系统异常！']);
            }
        }else{
            return response()->json(['status' => false, 'message' => '无效文件！']);
        }
    }

    /**
     * 标签上传完成
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadedLabels($id){
        try{
            DB::beginTransaction();
            $model = Delivery::query()->findOrFail($id);
            if(!$model || $model->status != 1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误(标签2)！']);
            }
            if($model->is_fnsku == 1 && $model->labels->isEmpty()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单无可下载标签！']);
            }
            $model->status = 2; //待备货
            $flag = $model->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 标签上传完成",$id);
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 返回标签上传
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function backUploadLabels($id){
        try{
            DB::beginTransaction();
            $model = Delivery::query()->findOrFail($id);
            if(!$model || !in_array($model->status,[2,3,4,5])){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误(标签3)！']);
            }
            $model->status = 1; //待上传标签
            $flag = $model->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 返回上传标签",$id);
                DB::commit();
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    //备货（view）
    public function listStartPreparing($id){
        $delivery = Delivery::query()->findOrFail($id);
        if(!$delivery){
            return response()->json(['status' => false, 'message' => '发货单状态有误(备货1)！']);
        }
        $status = $delivery->status;
        if($delivery && $delivery->status == 2){
            try{
                DB::beginTransaction();
                $delivery->status = 3;
                $flag = $delivery->save();
                if(!$flag){
                    DB::rollBack();
                }else{
                    Logs::logs(self::LOG_FLAG,"发货单：{$delivery->delivery_no} 开始备货",$id);
                    DB::commit();
                }
            }catch (\Exception $e){
                report($e);
            }
        }
        return view('overseas-in.os-dropshipping.modal-prepare',compact('id','delivery','status'));
    }

    /**
     * 备货
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doPrepare($param){
        try{
            DB::beginTransaction();
            //发货单
            $model = Delivery::query()->findOrFail($param['id']);
            if(!$model || $model->status != 3){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误(备货2)！']);
            }
            $flag1 = false;
            foreach ($param['detail'] as $item){
                //发货单明细
                $detail = DeliveryDetail::query()->findOrFail($item['id']);
                $detail->ship_num += $item['ship_num'];
                if($detail->ship_num < 0)$detail->ship_num = 0;
                $flag2 = $detail->save();
                if(!$flag2){
                    $flag1 = false;
                    break;
                }
                $flag1 = true;
            }
            if(!$flag1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 备货中",$param['id']);
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    //备货完成(view)
    public function listPreparing($id){
        $delivery = Delivery::query()->findOrFail($id);
        $status = $delivery->status;
        return view('overseas-in.os-dropshipping.modal-prepare',compact('id','delivery','status'));
    }

    /**
     * 备货完成
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function prepared($id){
        try{
            DB::beginTransaction();
            $model = Delivery::query()->findOrFail($id);
            if(!$model || $model->status != 3){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误(备货3)！']);
            }
            $model->status = 4; //装箱信息待录入
            $flag = $model->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 备货完成",$id);
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 装箱信息(单个手动录入)（view）
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function addBoxDetail($id){
        return view('overseas-in.os-dropshipping-box.detail',compact('id'));
    }

    /**
     * 添加装箱信息(单个手动录入)
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doAddBoxDetail($param){
        try{
            $id = $param['id'];
            //发货单
            $d = Delivery::query()->find($id);
            if($d->status != 4){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败：发货单状态有误(装箱1)！']);
            }
            unset($param['id']);
            $data = [];
            $exist = [];
            $ddExist = [];
            $boxNoTotal = [];
            foreach($param as $item){
                if(!array_key_exists($item['box_no'],$boxNoTotal)){
                    $boxNoTotal[$item['box_no']] = $item['total'];
                }
                $key = $item['box_no'].'-'.$item['fnsku'];
                if(in_array($key,$exist)){
                    continue;
                }else{
                    $exist[] = $key;
                }
                if(!$item['total']){
                    return response()->json(['status' => false, 'message' => '操作失败：'.$item['total'].'不能为空或0']);
                }
                if(!array_key_exists($item['fnsku'],$ddExist)){
                    //发货单明细
                    $dd = DeliveryDetail::query()
                        ->where('delivery_no', $d->delivery_no)
                        ->where('fnsku', $item['fnsku'])
                        ->first();
                    if(!$dd){
                        return response()->json(['status' => false, 'message' => '操作失败：'.$item['fnsku'].'明细中不存在']);
                    }
                    $ddExist[$item['fnsku']] = [
                        'account_id' => $dd->account_id,
                        'psku_id' => $dd->psku_id
                    ];
                }
                $data[$item['box_no']][$item['fnsku']]['account_id'] = $ddExist[$item['fnsku']]['account_id'];
                $data[$item['box_no']][$item['fnsku']]['psku_id'] = $ddExist[$item['fnsku']]['psku_id'];
                $data[$item['box_no']][$item['fnsku']]['total'] = $boxNoTotal[$item['box_no']];
                $data[$item['box_no']][$item['fnsku']]['num_per_box'] = $item['num_per_box'];
            }
            DB::beginTransaction();
            foreach($data as $boxNo => $boxDatum){
                $total = $boxNoTotal[$boxNo];
                foreach ($boxDatum as $fnSku => $item){
                    //发货单装箱
                    $boxItem = DeliveryBox::query()->firstOrNew([
                        'delivery_no' => $d->delivery_no,
                        'box_no' => $boxNo,
                        'fnsku' => $fnSku,
                    ],[
                        'batch_no' => $d->batch_no,
                        'delivery_type' => $d->delivery_type,
                        'plat_id' => $d->plat_id,
                        'area_id' => $d->area_id,
                        'warehouse_id' => $d->warehouse_id,
                        'psku_id' => $item['psku_id'],
                        'account_id' => $item['account_id'],
                        'total' => $total,
                        'num_per_box' => $item['num_per_box'],
                    ]);
                    $flag = $boxItem->save();
                    if(!$flag){
                        DB::rollBack();
                        break;
                    }
                }
                $boxSpecModel = DeliveryBox::query()
                    ->where('delivery_no', $d->delivery_no)
                    ->where('box_no', $boxNo)
                    ->where('long', '>', 0)
                    ->first();
                $boxSpec = [
                    'long' => $boxSpecModel->long ?? 0,
                    'wide' => $boxSpecModel->wide ?? 0,
                    'high' => $boxSpecModel->high ?? 0,
                    'weight' => $boxSpecModel->weight ?? 0
                ];
                $boxes = DeliveryBox::query()
                    ->where('delivery_no' , $d->delivery_no)
                    ->where('box_no' , $boxNo)
                    ->get();
                foreach ($boxes as $box){
                    $box->total = $total;
                    $box->long = $boxSpec['long'];
                    $box->wide = $boxSpec['wide'];
                    $box->high = $boxSpec['high'];
                    $box->weight = $boxSpec['weight'];
                    $box->save();
                    DeliveryBoxDetail::query()
                        ->where('delivery_box_id',$box->id)
                        ->where('p_index','>',$box->total)
                        ->delete();
                    for($index = 1; $index <= $box->total; $index++){
                        $indexCount = DeliveryBoxDetail::query()
                            ->where('delivery_box_id', $box->id)
                            ->where('p_index', $index)
                            ->count();
                        if($indexCount == 0){
                            DeliveryBoxDetail::query()->create([
                                'delivery_box_id' => $box->id,
                                'p_index' => $index,
                            ]);
                        }
                    }
                }
            }

            //更新发货单
            $totalBox = DeliveryBox::query()->where('delivery_no',$d->delivery_no)->sum('total');
            $d->total_box = $totalBox;
            $d->save();
            DB::commit();
            return response()->json(['status' => true, 'message' => '操作成功！']);
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function delBox($param){
        try{
            list($deliveryNo,$boxNo) = explode('_',$param);
            $delivery = Delivery::query()->where('delivery_no',$deliveryNo)->first();
            if($delivery->status != 4){
                return response()->json(['status' => false, 'message' => '操作失败：发货单状态有误！']);
            }
            DB::beginTransaction();
            $dbs = DeliveryBox::query()
                ->where('delivery_no',$deliveryNo)
                ->where('box_no',$boxNo)
                ->get();
            $total = 0;
            foreach ($dbs as $db){
                $total += $db->total;
                $db->delete();
            }
            $delivery->total_box -= min($delivery->total_box,$total);
            $delivery->save();
            DB::commit();
            return response()->json(['status' =>true, 'message' => '操作成功！']);
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 添加装箱明细（录入完成）
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function addedBoxDetail($id){
        try{
            DB::beginTransaction();
            $model = Delivery::query()->findOrFail($id);
            if($model->status != 4){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败：发货单状态有误！']);
            }
            //if(!$model->batch_no){
            //    DB::rollBack();
            //    return response()->json(['status' => false, 'message' => '操作失败：请先录入批次号！']);
            //}

            $fnSkuDetailCount = $model->detail->count();
            $fnSkuBoxCount = DeliveryBox::query()
                ->where('delivery_no',$model->delivery_no)
                ->distinct('fnsku')
                ->count();
            if($fnSkuDetailCount != $fnSkuBoxCount){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败：请确保所有产品均装箱！']);
            }
            $boxErrorCount = DeliveryBox::query()
                ->where('delivery_no',$model->delivery_no)
                ->where(function($query) {
                    $query->orWhere('long', 0)
                        ->orWhere('wide', 0)
                        ->orWhere('high', 0)
                        ->orWhere('weight', 0);
                })->count();
            if($boxErrorCount > 0){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败：箱规有误(不能为0)！']);
            }
            foreach ($model->detail as $detail){
                $deliveryBoxObj = DeliveryBox::query()
                    ->where('delivery_no',$model->delivery_no)
                    ->where('fnsku',$detail->fnsku)
                    ->selectRaw('SUM(total*num_per_box) AS ship_num')
                    ->first();
                $shipNum = $deliveryBoxObj->ship_num ?: 0;
                if($detail->ship_num != $shipNum){
                    //验证发货数量是否一致：(明细中的实际发货数量 == 箱规格中的总发货数量)
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败：发货数量与装箱后总数量不一致！']);
                }
            }
            $model->status = 5; //待发货
            $flag = $model->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 装箱信息录入完成",$id);
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 校检发货状态
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkDeliveryStatus($id){
        try{
            $delivery = Delivery::query()->find($id);
            if(!$delivery){
                return response()->json(['status' => false, 'message' => '操作失败：发货单不存在！']);
            }
            if($delivery->status != 4){ //装箱信息待录入
                return response()->json(['status' => false, 'message' => '操作失败：发货单状态有误！']);
            }else{
                return response()->json(['status' =>true, 'message' => '验证成功！']);
            }
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 发货
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function ship($id){
        //try{
        //    DB::beginTransaction();
            $model = Delivery::query()->findOrFail($id);
            if(!$model || $model->status != 5){
                //DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误！']);
            }
            if(!$model->detail) return response()->json(['status' => false, 'message' => '发货单明细不能为空！']);
            if(!$model->box) return response()->json(['status' => false, 'message' => '发货单装箱规格信息不能为空！']);
            if(!$model->logistics) return response()->json(['status' => false, 'message' => '发货单物流信息不能为空！']);

            $userId = Admin::user()->id;
            $shipTotalUnit = 0;
            $totalUnitPrice = 0;
            $placingDetail = [];
            $flag1 = false;
            foreach($model->detail as $k => $detail){
                //库存差额数据回写
                $flag2 = $this->_shipRewrite($userId,$model->area_id,$detail->psku_id,$detail->apply_num,$detail->ship_num,$model);
                if(!$flag2){
                    $flag1 = false;
                    break;
                }
                //海外仓在途库存数据回写
                $flag3 = $this->_shipFNSkuRewrite($model->warehouse_id,$detail->account_id,$detail->psku_id,$detail->fnsku,$detail->ship_num,$model);
                if(!$flag3){
                    $flag1 = false;
                    break;
                }
                $shipTotalUnit += $detail->ship_num;
                $totalUnitPrice += $detail->unit_price * $detail->ship_num;
                //出库明细
                $placingDetail[$k]['order_no'] = $detail->delivery_no;
                $placingDetail[$k]['detail_id'] = $detail->id;
                $placingDetail[$k]['psku_id'] = $detail->psku_id;
                $placingDetail[$k]['placing_num'] = $detail->ship_num;
                $placingDetail[$k]['unit_price'] = $detail->unit_price;
                $flag1 = true;
            }
            if(!$flag1){
                //DB::rollBack();
                return response()->json(['status' => false, 'message' => '库存异常！']);
            }

            //if ($model->plat_id == SysPlat::PLAT_RAKUTEN) {
            //    //将rakuten发货单同步至海外仓(谷仓)
            //    $requestStaus = OverseasInboundOrder::createGrn($model->delivery_no);
            //    if ($requestStaus == false) {
            //        DB::rollBack();
            //        return response()->json(['status' => false, 'message' => '海外仓订单,同步异常！']);
            //    }
            //}

            //发货单
            $model->status = 6; //已发货
            $model->delivered_at = date('Y-m-d H:i:s');
            $model->ship_total_unit = $shipTotalUnit;
            $model->total_unit_price = $totalUnitPrice;
            $flag3 = $model->save();
            if(!$flag3){
                //DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败-1！']);
            }

            //国内库存出库记录
            $placing = Placing::create([
                'placing_no' => SerialNo::getPlNo(),
                'placing_at' => date('Y-m-d'),
                'cuser_id' => $userId
            ]);
            $placing->detail()->createMany($placingDetail);
            if($placing = 1){
                //DB::commit();
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 已发货",$id);
                return response()->json(['status' => true,'message' => '操作成功！']);
            }else{
                //DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败-2！']);
            }
        //}catch (QueryException $qe){
        //    DB::rollBack();
        //    report($qe);
        //    return response()->json(['status' => false, 'message' => $qe->getMessage()]);
        //}catch (\Exception $e){
        //    DB::rollBack();
        //    report($e);
        //    return response()->json(['status' => false, 'message' => $e->getMessage()]);
        //}
    }

    /**
     * *发货*
     * 海外仓在途库存数据回写
     * @param $warehouseId
     * @param $accountId
     * @param $pSkuId
     * @param $fnSku
     * @param $shipNum
     * @param $deliveryObj
     * @return bool
     */
    private function _shipFNSkuRewrite($warehouseId,$accountId,$pSkuId,$fnSku,$shipNum,$deliveryObj){
        //海外仓-代发FNSKU库存
        $inventory = DropshippingInventoryFnsku::query()
            ->firstOrNew([
                'plat_id' => $deliveryObj->plat_id,
                'warehouse_id' => $warehouseId,
                'account_id' => $accountId,
                'fnsku' => $fnSku,
            ],[
                'psku_id' => $pSkuId
            ]);
        $inventory->transit += $shipNum;
        $flag = $inventory->save();
        if(!$flag)return false;
        return true;
    }

    /**
     * *发货*
     * 库存差额数据回写
     * @param $userId
     * @param $areaId
     * @param $pSkuId
     * @param $applyNum
     * @param $shipNum
     * @param $deliveryObj
     * @return bool
     */
    private function _shipRewrite($userId,$areaId,$pSkuId,$applyNum,$shipNum,$deliveryObj){
        //国内库存
        $inventory = InventoryCn::query()
            ->where('area_id', $areaId)
            ->where('psku_id', $pSkuId)
            ->lockForUpdate()
            ->first();
        if(!$inventory){
            return false;
        }
        $inventory->reserve -= min($inventory->reserve,$applyNum);
        $inventory->instant += $applyNum - $shipNum;
        $flag1 = $inventory->save();
        if(!$flag1){
            return false;
        }
        //库存出入库记录
        $flag2 = Record::create([
            'record_no' => SerialNo::getRcNo(),
            'psku_id' => $pSkuId,
            'area_id' => $areaId,
            'action_type' => 4,
            'record_type' => 2,
            'num' => -$shipNum,
            'user_id' => $userId,
        ]);
        if(!$flag2){
            return false;
        }
        return true;
    }

    //更新物流（view）
    public function listLogistics($id){
        $delivery = Delivery::query()->findOrFail($id);
        return view('overseas-in.os-dropshipping.modal-logistics',compact('id','delivery'));
    }

    //更新物流
    public function doLogistics($param){
        try{
            DB::beginTransaction();
            $delivery = Delivery::query()->findOrFail($param['id']);
            if(!in_array($delivery->status,[4,5,6,7])){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误！']);
            }

            if (!$param['express_company_id'] || !$param['express_channel_id']) {
                return response()->json(['status' => false, 'message' => '物流公司/渠道不能为空！']);
            }
            if (!$param['tracking_no']) {
                return response()->json(['status' => false, 'message' => '追踪号不能为空！']);
            }
            if (!$param['arrived_at']) {
                return response()->json(['status' => false, 'message' => '到货时间不能为空！']);
            }

            $item = [
                'express_company_id' => $param['express_company_id'],
                'area_id' => $delivery->area_id,
                'express_channel_id' => $param['express_channel_id'],
                'tracking_no' => $param['tracking_no'],
                'total_weight' => $param['total_weight'],
                'shipping_fee' => $param['shipping_fee'],
                'other_fee' => $param['other_fee'],
            ];
            if($param['arrived_at']){
                $item['arrived_at'] = $param['arrived_at'];
            }

            //更新物流
            $osl = DeliveryLogistics::query()->updateOrCreate([
                'delivery_no' => $delivery->delivery_no
            ],$item);
            if(!$osl){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }

            $delivery->logistics_status = 2;
            if($osl->tracking_no){
                $delivery->track_ex_status = 2;//中转发货单的运单号状态（已录入）
                ////更新海外仓中转库存的物流运单号/追踪号
                //InventoryBox::query()
                //    ->where('batch_no',$delivery->batch_no)
                //    ->where('warehouse_id',$delivery->warehouse_id)
                //    ->update([
                //    'tracking_no' => $osl->tracking_no
                //]);
            }
            //更新发货单
            $flag = $delivery->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$delivery->delivery_no} 物流信息已更新",$delivery->id);
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    //更新运输
    public function listTransport($id){
        $delivery = Delivery::query()->findOrFail($id);
        $_transport = $delivery->transport->pluck('date_at','status')->toArray();
        $status = DeliveryTransport::$_status;
        $transport = [];
        foreach ($status as $key => $item){
            $transport[$key]['status'] = $item;
            $transport[$key]['date_at'] = array_key_exists($key,$_transport) ? $_transport[$key] : '';
        }
        return view('overseas-in.os-dropshipping.modal-up-transport',compact('id','delivery','transport'));
    }

    public function doUpTransport($param){
        try{
            DB::beginTransaction();
            $delivery = Delivery::query()->findOrFail($param['id']);
            if(!in_array($delivery->status,array_keys(Delivery::$_rStatus))){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误！']);
            }
            $max = $delivery->transport_status;
            foreach ($param['date_at'] as $status => $dateAt){
                if(!$dateAt)continue;
                if($max < $status){
                    $max = $status;
                }
                DeliveryTransport::query()->updateOrCreate(
                    ['delivery_no' => $delivery->delivery_no, 'status' => $status],
                    ['date_at' => $dateAt]
                );
            }
            $delivery->transport_status = $max;
            $flag = $delivery->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                Logs::logs(self::LOG_FLAG,"发货单：{$delivery->delivery_no} 运输信息已更新",$delivery->id);
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function listCheckTransport($id){
        $delivery = Delivery::query()->findOrFail($id);
        return view('overseas-in.os-dropshipping.modal-transport',compact('id','delivery'));
    }

    //EDIT
    /**
     * 删除标签
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delLabels($id){
        try{
            DB::beginTransaction();
            list($deliveryId,$labelsId) = explode('-',$id);
            $delivery = Delivery::query()->findOrFail($deliveryId);
            if($delivery->status != 1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误！']);
            }
            $labels = DeliveryLabels::query()->findOrFail($labelsId);
            if($labels){
                $uploadFile = UploadFile::getInit();
                $flag1 = $uploadFile->delFile($labels->d_labels);
                $flag = $flag1 && $labels->delete();
            }else{
                $flag = true;
            }
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 上传标签
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function uploadLabels($id){
        return view('overseas-in.os-dropshipping-edit.modal-labels',compact('id'));
    }

    //备货
    public function startPreparing($id){
        $delivery = Delivery::query()->findOrFail($id);
        $status = $delivery->status;
        if($delivery && $delivery->status == 2){
            try{
                DB::beginTransaction();
                $delivery->status = 3;
                $flag = $delivery->save();
                if(!$flag){
                    DB::rollBack();
                }else{
                    Logs::logs(self::LOG_FLAG,"发货单：{$delivery->delivery_no} 开始备货",$id);
                    DB::commit();
                }
            }catch (\Exception $e){
                report($e);
            }
        }
        return view('overseas-in.os-dropshipping-edit.modal-prepare',compact('id','delivery','status'));
    }

    public function preparing($id){
        $delivery = Delivery::query()->findOrFail($id);
        $status = $delivery->status;
        return view('overseas-in.os-dropshipping-edit.modal-prepare',compact('id','delivery','status'));
    }

    /**
     * 更新物流
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function logistics($id){
        $delivery = Delivery::query()->findOrFail($id);
        return view('overseas-in.os-dropshipping-edit.modal-logistics',compact('id','delivery'));
    }


    /**
     * 删除中转发货单
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function osDel($id){
        try{
            DB::beginTransaction();
            $model = Delivery::query()->findOrFail($id);
            if(!$model || $model->status != 1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单状态有误！']);
            }
            $flag = false;
            foreach($model->detail as $detail){
                $inventory = InventoryCn::query()->where('area_id',$model->area_id)
                    ->where('psku_id',$detail->psku_id)
                    ->lockForUpdate()
                    ->first();
                if(!$inventory){
                    $flag = false;
                    break;
                }
                $inventory->reserve -= min($inventory->reserve,$detail->apply_num);
                $inventory->instant += $detail->apply_num;
                $flag1 = $inventory->save();
                if(!$flag1){
                    $flag = false;
                    break;
                }
                $flag = true;
            }
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                $model->delete();
                Logs::logs(self::LOG_FLAG,"发货单：{$model->delivery_no} 已删除",$id);
                DB::commit();
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }
        }catch (QueryException $qe){
            DB::rollBack();
            report($qe);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }
}
